# -*- coding: utf-8 -*-
import django
import uuid
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models import permalink
from django.contrib.auth.models import User, UserManager
from mptt.fields import TreeForeignKey
from mptt.models import MPTTModel
# Create your models here.
PAYMENT_STATUS=(
    (1,'预付'),
    (2,'现结'),
    (3,'提付'),
    (4,'记账'),
    (5,'返款'),
    (6,'垫付')
)
COMPANY_RANK=(
    ('headquarters','总部'),
    ('branch','分公司')
)
STATUS_CHOICES=(
    ('new','草稿'),
    ('approving','审核中'),
    ('need-edit','被驳回'),
    ('approved','已审核')
)
ZONE_LEVEL=(
    ('country','国家'),
    ('province','省(直辖市)'),
    ('city','市'),
    ('county','县区')
)
class Company(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=128,verbose_name="名称")
    place = models.CharField(verbose_name='地点',max_length=64)
    rank = models.CharField(max_length=32,choices=COMPANY_RANK,default='branch', verbose_name='级别')
    #parent = TreeForeignKey('self', null=True, blank=True,related_name='children')
    sort_order = models.IntegerField(default=1,verbose_name='排序')
    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '组织结构'
        verbose_name_plural = '组织结构'
    #class MPTTMeta:
    #    order_insertion_by = ['order']

    #def save(self, *args, **kwargs):
    #    super(Company, self).save(*args, **kwargs)
    #    Company.objects.rebuild()
class Country(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    code = models.CharField(max_length=32,verbose_name="代码", unique=True)
    name = models.CharField(max_length=128,verbose_name="名称")
    def __unicode__(self):
        return '%s[%s]'%(self.name,self.code)
    def __str__(self):
        return '%s[%s]'%(self.name,self.code)
    class Meta:
        verbose_name = '国家'
        verbose_name_plural = '国家'
class Brand(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200,verbose_name='名称', unique=True)
    country = models.ForeignKey(Country,verbose_name='国家')
    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '品牌'
        verbose_name_plural = '品牌'
class Vehicle(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    brand = models.ForeignKey(Brand,verbose_name='品牌')
    name = models.CharField(max_length=200,verbose_name='型号')
    year = models.IntegerField(verbose_name='上市年份',blank=True)
    is_import = models.BooleanField(verbose_name='是否进口',default=False)
    def __unicode__(self):
        return '[%s]%s'%(self.brand,self.name)
    def __str__(self):
        return '[%s]%s'%(self.brand,self.name)
    class Meta:
        verbose_name='车辆'
        verbose_name_plural='车辆'

class Agent(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200,verbose_name='名字')
    phone = models.CharField(max_length=32, verbose_name="电话")
    email = models.EmailField(max_length=32, verbose_name="邮件",blank=True)
    address = models.CharField(max_length=256, verbose_name="地址",blank=True)
    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '委托方'
        verbose_name_plural = '委托方'

class Carrier(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200,verbose_name='名字')
    phone = models.CharField(max_length=32, verbose_name="电话")
    email = models.EmailField(max_length=32, verbose_name="邮件",blank=True)
    address = models.CharField(max_length=256, verbose_name="地址",blank=True)
    company = models.ForeignKey(Company,verbose_name='公司')
    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '承运人'
        verbose_name_plural = '承运人'
class Counterman(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200,verbose_name='名字')
    phone = models.CharField(max_length=32, verbose_name="电话")
    email = models.EmailField(max_length=32, verbose_name="邮件",blank=True)
    address = models.CharField(max_length=256, verbose_name="地址",blank=True)
    company = models.ForeignKey(Company,verbose_name='公司')
    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '业务员'
        verbose_name_plural = '业务员'

class Waybill(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    ticket = models.CharField(max_length=200,verbose_name='单号', unique=True)
    ticket_at = models.DateField(verbose_name='日期')
    agent = models.ForeignKey(Agent,verbose_name='委托方')
    start_place = models.CharField(max_length=20,verbose_name='起运地')
    end_place = models.CharField(max_length=20,verbose_name='目的地')
    other_cost = models.DecimalField(max_digits=20,decimal_places=2,blank=True,default=0.00,verbose_name='其他费用')
    other_cost2 = models.DecimalField(max_digits=20,decimal_places=2,blank=True,default=0.00,verbose_name='其他费用2')
    other_cost3 = models.DecimalField(max_digits=20,decimal_places=2,blank=True,default=0.00,verbose_name='其他费用3')
    receipt_cost = models.DecimalField(max_digits=20,decimal_places=2,verbose_name='合计应收')
    collection_cost = models.DecimalField(max_digits=20,decimal_places=2,blank=True,default=0.00,verbose_name='代收款')
    payment_status=models.IntegerField(choices=PAYMENT_STATUS,verbose_name='付款状态')
    remark = models.TextField(max_length=2000,blank=True,verbose_name='备注')
    receipt_ticket = models.CharField(max_length=20,blank=True,verbose_name='收款单号')
    counterman = models.ForeignKey(Counterman,blank=True,verbose_name='业务归属')
    
    created_by = models.ForeignKey(django.contrib.auth.models.User, editable = False, verbose_name = '创建人', related_name='waybills')
    created_at = models.DateTimeField(verbose_name = '创建时间', auto_now_add = True, editable = False)
    updated_by = models.ForeignKey(django.contrib.auth.models.User, editable = False, verbose_name = '修改人', related_name='update_waybills')
    updated_at = models.DateTimeField(verbose_name = '修改时间', auto_now_add = True, editable = False)    
    
    
    status = models.CharField(max_length=32,choices=STATUS_CHOICES,default='new',editable=False, verbose_name='状态')
    @permalink
    def get_absolute_url(self):
        return ("waybill",(),{'id':self.id})
    def __unicode__(self):
        return '%s[%s]'%(self.ticket,self.ticket_at)
    def __str__(self):
        return '%s[%s]'%(self.ticket,self.ticket_at)
    class Meta:
        verbose_name = '承运总单'
        verbose_name_plural = '承运总单'

class WaybillItem(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    vehicle = models.ForeignKey(Vehicle, verbose_name='车辆')
    #quantity = models.IntegerField(verbose_name='数量')
    vin = models.CharField(max_length=32,verbose_name='车架号',blank=True)
    cost = models.DecimalField(max_digits=20,decimal_places=2,verbose_name='单价')
    waybill = models.ForeignKey(Waybill,related_name='items')
    def __unicode__(self):
       return '%s (%s)'%(self.vehicle,self.cost)
    def __str__(self):
       return '%s (%s)'%(self.vehicle,self.cost)
    class Meta:
        verbose_name = '承运车辆'
        verbose_name_plural = '承运车辆'

class Clerk(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200,verbose_name='名字')
    phone = models.CharField(max_length=32, verbose_name="电话")
    email = models.EmailField(max_length=32, verbose_name="邮件",blank=True)
    address = models.CharField(max_length=256, verbose_name="地址",blank=True)
    company = models.ForeignKey(Company,verbose_name='公司')
    def __unicode__(self):
        return self.name
    def __str__(self):
        return self.name
    class Meta:
        verbose_name = '记账员'
        verbose_name_plural = '记账员'

class WaybillPart(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    clerk = models.ForeignKey(Clerk,verbose_name='账目归属')
    waybill = models.ForeignKey(Waybill,related_name='parts')
    start_place = models.CharField(max_length=20,verbose_name='起运地')
    end_place = models.CharField(max_length=20,verbose_name='目的地')
    carrier = models.ForeignKey(Carrier,verbose_name='承运人')
    other_cost = models.DecimalField(max_digits=20,decimal_places=2,blank=True,default=0.00,verbose_name='其他费用')
    other_cost2 = models.DecimalField(max_digits=20,decimal_places=2,blank=True,default=0.00,verbose_name='其他费用2')
    other_cost3 = models.DecimalField(max_digits=20,decimal_places=2,blank=True,default=0.00,verbose_name='其他费用3')
    receipt_cost = models.DecimalField(max_digits=20,decimal_places=2,verbose_name='合计应收')
    collection_cost = models.DecimalField(max_digits=20,decimal_places=2,blank=True,default=0.00,verbose_name='代收款')
    payment_status=models.IntegerField(choices=PAYMENT_STATUS,verbose_name='付款状态')
    remark = models.TextField(max_length=2000,blank=True,verbose_name='备注')
    payment_ticket = models.CharField(max_length=20,blank=True,verbose_name='付款单号')
    
    created_by = models.ForeignKey(django.contrib.auth.models.User, editable = False, verbose_name = '创建人', related_name='waybillparts')
    created_at = models.DateTimeField(verbose_name = '创建时间', auto_now_add = True, editable = False)
    updated_by = models.ForeignKey(django.contrib.auth.models.User, editable = False, verbose_name = '修改人', related_name='update_waybillparts')
    updated_at = models.DateTimeField(verbose_name = '修改时间', auto_now_add = True, editable = False)    
    
    def __unicode__(self):
        return '[%s]%s-%s'%(self.waybill,self.start_place,self.end_place)
    def __str__(self):
        return '[%s]%s-%s'%(self.waybill,self.start_place,self.end_place)
    class Meta:
        verbose_name = '承运分单'
        verbose_name_plural = '承运分单'


class WaybillPartItem(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    waybillitem = models.ForeignKey(WaybillItem, verbose_name='承运车辆')
    # vehicle = models.ForeignKey(Vehicle, verbose_name=_('车辆'))
    # vin = models.CharField(max_length=32,verbose_name=_('车架号'),blank=True)
    cost = models.DecimalField(max_digits=20,decimal_places=2,verbose_name='单价')
    waybillpart = models.ForeignKey(WaybillPart,related_name='items',verbose_name='承运分单')
    def __unicode__(self):
       return '%s (%s)'%(self.waybillitem,self.cost)
    def __str__(self):
       return '%s (%s)'%(self.waybillitem,self.cost)
    class Meta:
        verbose_name = '分单承运车辆'
        verbose_name_plural = '分单承运车辆'
        
class UserProfile(models.Model):  
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(User)
    company = models.ForeignKey(Company, verbose_name='公司')
    def __unicode__(self):
       return '%s (%s)'%(self.user.username,self.company.name)
    def __str__(self):
       return '%s (%s)'%(self.user.username,self.company.name)
    class Meta:
        verbose_name = '人员分配'
        verbose_name_plural = '人员分配'
        
class ApproveLog(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_by = models.ForeignKey(django.contrib.auth.models.User, editable = False, verbose_name = '创建人', related_name='approveLog')
    waybill = models.ForeignKey(Waybill,verbose_name='承运总单',editable = False)
    created_at = models.DateTimeField(verbose_name = '创建时间', auto_now_add = True, editable = False)
    action = models.CharField(max_length=32,verbose_name='动作', editable = False)
    def __unicode__(self):
       return '%s %s'%(self.action,self.waybill)
    def __str__(self):
       return '%s %s'%(self.action,self.waybill)
    class Meta:
        verbose_name = '审核日志'
        verbose_name_plural = '审核日志'    
    
# class Category(MPTTModel):
#     name = models.CharField(max_length=64)
#     slug = models.CharField(max_length=64)
#     parent = TreeForeignKey('self', null=True, blank=True,
#                             related_name='children')
#     is_active = models.BooleanField()
#     order = models.IntegerField()

#     def __unicode__(self):
#         return self.name
#     def __str__(self):
#         return self.name
#     class Meta:
#         verbose_name_plural = "Categories"

#     class MPTTMeta:
#         order_insertion_by = ['order']

#     def save(self, *args, **kwargs):
#         super(Category, self).save(*args, **kwargs)
#         Category.objects.rebuild()